<template>
  <view class="detail-container">
    <!-- 自定义顶部导航栏 -->
    <view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-left" @click="goBack">
        <view class="back-icon">
          <image src="https://cdn-icons-png.flaticon.com/512/271/271220.png" class="back-arrow-icon"></image>
        </view>
      </view>
      <view class="nav-title" :style="{ color: getCategoryColor() }">
        {{ categoryTitle }}
      </view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 内容区域 -->
    <view class="content-area" :style="{ paddingTop: (statusBarHeight + 88) + 'px' }">
      <!-- 任务状态提示 -->
      <view class="task-status">
        <text class="status-text">今日{{ categoryTitle }}清单有 <text class="highlight" :style="{ color: getCategoryColor() }">{{ overdueCount }}</text> 项延期，请尽快完成！</text>
        
        <!-- 日期选择器 - 使用在线图标 -->
        <view class="date-selector" @click="showDatePicker">
          <view class="date-icon">
            <image src="https://cdn-icons-png.flaticon.com/512/2693/2693507.png" class="calendar-icon"></image>
          </view>
          <text class="date-text">{{ formattedDate }}</text>
          <view class="arrow-icon">
            <image src="https://cdn-icons-png.flaticon.com/512/32/32195.png" class="arrow-down-icon"></image>
          </view>
        </view>
      </view>
      
      <!-- 任务列表 -->
      <view class="task-list">
        <task-item
          v-for="task in tasks"
          :key="task.id"
          :task="task"
          :swipe-threshold="swipeThreshold"
          @touch-start="handleTaskTouchStart"
          @update-offset="updateTaskOffset"
          @toggle-complete="toggleTaskStatus"
          @edit="showEditTaskModal"
          @delete="showDeleteConfirm"
        />
      </view>
    </view>
    
    <!-- 日期选择弹窗 -->
    <view v-if="showDatePickerPopup" class="popup-mask" @click="closeDatePicker"></view>
    <view v-if="showDatePickerPopup" class="popup-content date-picker-popup">
      <view class="date-picker-container">
        <view class="picker-header">
          <text class="cancel-btn" @click="closeDatePicker">取消</text>
          <text class="picker-title">选择日期</text>
          <text class="confirm-btn" @click="confirmDateSelection">确定</text>
        </view>
        <picker-view
          :indicator-style="'height: 50px;'"
          :value="datePickerValue"
          @change="onDatePickerChange"
          class="picker-view"
        >
          <picker-view-column>
            <view class="picker-item" v-for="(year, index) in years" :key="'year-'+index">{{ year }}年</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(month, index) in months" :key="'month-'+index">{{ month }}月</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(day, index) in days" :key="'day-'+index">{{ day }}日</view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
    
    <!-- 添加任务弹窗 -->
    <view v-if="showAddTaskModalVisible" class="popup-mask" @click="closeAddTaskModal"></view>
    <view v-if="showAddTaskModalVisible" class="popup-content modal-popup">
      <view class="task-modal">
        <view class="modal-header">
          <text class="modal-title">添加任务</text>
        </view>
        <view class="modal-content">
          <view class="input-group">
            <text class="input-label">任务名称</text>
            <input class="input-field" v-model="newTask.title" placeholder="请输入任务名称" />
          </view>
          <view class="input-group">
            <text class="input-label">任务描述</text>
            <input class="input-field" v-model="newTask.description" placeholder="请输入任务描述" />
          </view>
          <view class="input-group">
            <text class="input-label">任务时间</text>
            <picker
              mode="time"
              :value="newTask.time"
              @change="onTimeChange"
              class="time-picker"
            >
              <view class="picker-value">{{ newTask.time || '请选择时间' }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <button class="cancel-button" @click="closeAddTaskModal">取消</button>
          <button class="confirm-button" @click="addTask">确定</button>
        </view>
      </view>
    </view>
    
    <!-- 编辑任务弹窗 -->
    <view v-if="showEditTaskModalVisible" class="popup-mask" @click="closeEditTaskModal"></view>
    <view v-if="showEditTaskModalVisible" class="popup-content modal-popup">
      <view class="task-modal">
        <view class="modal-header">
          <text class="modal-title">编辑任务</text>
        </view>
        <view class="modal-content">
          <view class="input-group">
            <text class="input-label">任务名称</text>
            <input class="input-field" v-model="editingTask.title" placeholder="请输入任务名称" />
          </view>
          <view class="input-group">
            <text class="input-label">任务描述</text>
            <input class="input-field" v-model="editingTask.description" placeholder="请输入任务描述" />
          </view>
          <view class="input-group">
            <text class="input-label">任务时间</text>
            <picker
              mode="time"
              :value="editingTask.time"
              @change="onEditTimeChange"
              class="time-picker"
            >
              <view class="picker-value">{{ editingTask.time || '请选择时间' }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <button class="cancel-button" @click="closeEditTaskModal">取消</button>
          <button class="confirm-button" @click="updateTask">确定</button>
        </view>
      </view>
    </view>
    
    <!-- 删除确认弹窗 -->
    <view v-if="showDeleteConfirmVisible" class="popup-mask" @click="closeDeleteConfirm"></view>
    <view v-if="showDeleteConfirmVisible" class="popup-content modal-popup">
      <view class="confirm-modal">
        <view class="confirm-title">确认删除</view>
        <view class="confirm-content">确定要删除这个任务吗？</view>
        <view class="confirm-buttons">
          <button class="cancel-button" @click="closeDeleteConfirm">取消</button>
          <button class="delete-button" @click="deleteTask">删除</button>
        </view>
      </view>
    </view>
    
    <!-- 添加任务按钮 -->
    <view class="add-task-btn" @click="showAddTaskModal">
      <text>添加任务</text>
    </view>
  </view>
</template>

<script>
import TaskItem from '@/components/TaskItem/TaskItem.vue'

export default {
  components: {
    TaskItem
  },
  data() {
    const currentDate = new Date()
    const currentYear = currentDate.getFullYear()
    const currentMonth = currentDate.getMonth() + 1
    const currentDay = currentDate.getDate()

    return {
      statusBarHeight: 0, // 状态栏高度
      categoryId: null,
      categoryTitle: "学习",
      overdueCount: 1,
      selectedDate: {
        year: currentYear,
        month: currentMonth,
        day: currentDay,
      },
      datePickerValue: [9, 9, 13], // 默认为10月14日（索引从0开始）
      years: Array.from({ length: 10 }, (_, i) => currentYear - 5 + i),
      months: Array.from({ length: 12 }, (_, i) => i + 1),
      days: Array.from({ length: 31 }, (_, i) => i + 1),
      tasks: [
        {
          id: 1,
          title: "C4D直播课",
          description: "新插件下载",
          time: "19:30",
          completed: false,
          offsetX: 0,
        },
        {
          id: 2,
          title: "动效小作业",
          description: "提前完成再做一个MG小动画",
          time: "16:30",
          completed: true,
          offsetX: 0,
        },
        {
          id: 3,
          title: "看公众号推文",
          description: "总结记录",
          time: "10:30",
          completed: true,
          offsetX: 0,
        },
      ],
      activeTaskId: null,
      swipeThreshold: -160, // 滑动阈值
      newTask: {
        title: "",
        description: "",
        time: "",
      },
      editingTask: {
        id: null,
        title: "",
        description: "",
        time: "",
      },
      deleteTaskId: null,
      categoryColors: {
        学习: "#FFCD00",
        生活: "#7766E7",
        工作: "#518BF1",
        社交: "#FE748B",
        健康: "#1EBD85",
        其他: "#C4C4C4",
      },
      // 弹窗状态控制
      showDatePickerPopup: false,
      showAddTaskModalVisible: false,
      showEditTaskModalVisible: false,
      showDeleteConfirmVisible: false,
    }
  },
  computed: {
    formattedDate() {
      return `${this.selectedDate.month}-${this.selectedDate.day}`
    },
  },
  onLoad(options) {
    // 获取状态栏高度
    this.getStatusBarHeight()
    
    // 从路由参数获取分类ID和标题
    if (options.id) {
      this.categoryId = options.id
    }
    if (options.title) {
      this.categoryTitle = decodeURIComponent(options.title)
    }

    // 加载该分类下的任务
    this.loadTasks()
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      try {
        // 声明 uni 变量
        const uni = window.uni || (typeof uni !== 'undefined' ? uni : {});
        const systemInfo = uni.getSystemInfoSync()
        this.statusBarHeight = systemInfo.statusBarHeight || 0
      } catch (e) {
        console.error('获取系统信息失败', e)
        this.statusBarHeight = 20 // 默认值
      }
    },
    
    // 返回上一页
    goBack() {
      // 声明 uni 变量
      const uni = window.uni || (typeof uni !== 'undefined' ? uni : {});
      uni.navigateBack()
    },

    // 获取分类颜色
    getCategoryColor() {
      return this.categoryColors[this.categoryTitle] || "#FFCD00"
    },

    // 加载任务数据
    loadTasks() {
      // 这里应该根据categoryId和selectedDate从数据源加载任务
      // 示例中使用的是静态数据，实际应用中可能需要从API或本地存储获取
      console.log(`加载${this.categoryTitle}分类在${this.formattedDate}的任务`)

      // 计算逾期任务数量
      this.overdueCount = this.tasks.filter((task) => !task.completed).length
    },

    // 处理任务触摸开始
    handleTaskTouchStart(taskId) {
      this.activeTaskId = taskId
      
      // 重置其他项的偏移
      this.tasks.forEach((task) => {
        if (task.id !== taskId) {
          task.offsetX = 0
        }
      })
    },

    // 更新任务偏移量
    updateTaskOffset(taskId, offsetX) {
      const taskIndex = this.tasks.findIndex(task => task.id === taskId)
      if (taskIndex !== -1) {
        this.tasks[taskIndex].offsetX = offsetX
      }
    },

    // 显示日期选择器
    showDatePicker() {
      this.showDatePickerPopup = true
    },

    // 关闭日期选择器
    closeDatePicker() {
      this.showDatePickerPopup = false
    },

    // 日期选择器变化事件
    onDatePickerChange(e) {
      const values = e.detail.value
      this.datePickerValue = values
    },

    // 确认日期选择
    confirmDateSelection() {
      const [yearIndex, monthIndex, dayIndex] = this.datePickerValue
      this.selectedDate = {
        year: this.years[yearIndex],
        month: this.months[monthIndex],
        day: this.days[dayIndex],
      }

      // 重新加载选定日期的任务
      this.loadTasks()
      this.closeDatePicker()
    },

    // 切换任务完成状态
    toggleTaskStatus(taskId) {
      const taskIndex = this.tasks.findIndex(task => task.id === taskId)
      if (taskIndex !== -1) {
        this.tasks[taskIndex].completed = !this.tasks[taskIndex].completed
        // 更新逾期任务数量
        this.overdueCount = this.tasks.filter((task) => !task.completed).length
      }
    },

    // 显示添加任务弹窗
    showAddTaskModal() {
      this.newTask = {
        title: "",
        description: "",
        time: "",
      }
      this.showAddTaskModalVisible = true
    },

    // 关闭添加任务弹窗
    closeAddTaskModal() {
      this.showAddTaskModalVisible = false
    },

    // 时间选择器变化事件
    onTimeChange(e) {
      this.newTask.time = e.detail.value
    },

    // 添加新任务
    addTask() {
      // 声明 uni 变量
      const uni = window.uni || (typeof uni !== 'undefined' ? uni : {});
      if (!this.newTask.title) {
        uni.showToast({
          title: "请输入任务名称",
          icon: "none",
        })
        return
      }

      const newTaskObj = {
        id: Date.now(),
        title: this.newTask.title,
        description: this.newTask.description,
        time: this.newTask.time,
        completed: false,
        offsetX: 0,
      }

      // 添加到任务列表
      this.tasks.push(newTaskObj)

      // 更新逾期任务数量
      this.overdueCount = this.tasks.filter((task) => !task.completed).length

      // 关闭弹窗
      this.closeAddTaskModal()

      uni.showToast({
        title: "添加成功",
        icon: "success",
      })
    },

    // 显示编辑任务弹窗
    showEditTaskModal(taskId) {
      const taskIndex = this.tasks.findIndex(task => task.id === taskId)
      if (taskIndex !== -1) {
        const task = this.tasks[taskIndex]
        this.editingTask = {
          id: task.id,
          title: task.title,
          description: task.description,
          time: task.time,
        }

        // 重置滑动状态
        this.updateTaskOffset(taskId, 0)

        this.showEditTaskModalVisible = true
      }
    },

    // 关闭编辑任务弹窗
    closeEditTaskModal() {
      this.showEditTaskModalVisible = false
    },

    // 编辑时间选择器变化事件
    onEditTimeChange(e) {
      this.editingTask.time = e.detail.value
    },

    // 更新任务
    updateTask() {
      // 声明 uni 变量
      const uni = window.uni || (typeof uni !== 'undefined' ? uni : {});
      if (!this.editingTask.title) {
        uni.showToast({
          title: "请输入任务名称",
          icon: "none",
        })
        return
      }

      const taskIndex = this.tasks.findIndex(task => task.id === this.editingTask.id)
      if (taskIndex !== -1) {
        this.tasks[taskIndex].title = this.editingTask.title
        this.tasks[taskIndex].description = this.editingTask.description
        this.tasks[taskIndex].time = this.editingTask.time

        // 关闭弹窗
        this.closeEditTaskModal()

        uni.showToast({
          title: "更新成功",
          icon: "success",
        })
      }
    },

    // 显示删除确认弹窗
    showDeleteConfirm(taskId) {
      this.deleteTaskId = taskId

      // 重置滑动状态
      this.updateTaskOffset(taskId, 0)

      this.showDeleteConfirmVisible = true
    },

    // 关闭删除确认弹窗
    closeDeleteConfirm() {
      this.showDeleteConfirmVisible = false
    },

    // 删除任务
    deleteTask() {
      // 声明 uni 变量
      const uni = window.uni || (typeof uni !== 'undefined' ? uni : {});
      if (this.deleteTaskId) {
        const taskIndex = this.tasks.findIndex(task => task.id === this.deleteTaskId)
        if (taskIndex !== -1) {
          this.tasks.splice(taskIndex, 1)

          // 更新逾期任务数量
          this.overdueCount = this.tasks.filter((task) => !task.completed).length

          // 关闭弹窗
          this.closeDeleteConfirm()

          uni.showToast({
            title: "删除成功",
            icon: "success",
          })
        }
      }
    },
  },
}
</script>

<style>
.detail-container {
  min-height: 100vh;
  background-color: #F8F8FB;
  position: relative;
  padding-bottom: 120rpx;
}

/* 自定义导航栏样式 */
.custom-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background-color: #F8F8FB;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-arrow-icon {
  width: 32rpx;
  height: 32rpx;
}

.nav-title {
  font-size: 52rpx;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

.nav-right {
  width: 60rpx;
}

/* 内容区域 */
.content-area {
  width: 100%;
}

/* 任务状态提示 */
.task-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
}

.status-text {
  font-size: 28rpx;
  color: #666;
  flex: 1;
}

.highlight {
  font-weight: bold;
}

/* 日期选择器样式 - 使用在线图标 */
.date-selector {
  display: flex;
  align-items: center;
  background-color: #FFFFFF;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.date-icon {
  margin-right: 10rpx;
}

.calendar-icon {
  width: 32rpx;
  height: 32rpx;
}

.date-text {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}

.arrow-icon {
  display: flex;
  align-items: center;
}

.arrow-down-icon {
  width: 20rpx;
  height: 20rpx;
}

/* 任务列表 */
.task-list {
  padding: 20rpx 30rpx;
}

/* 弹窗样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 998;
}

.popup-content {
  position: fixed;
  z-index: 999;
}

.date-picker-popup {
  left: 0;
  right: 0;
  bottom: 0;
}

.modal-popup {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 日期选择器弹窗 */
.date-picker-container {
  background-color: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
}

.picker-header {
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
}

.confirm-btn {
  color: #7766E7;
  font-size: 32rpx;
}

.picker-view {
  height: 400rpx;
  width: 100%;
  margin-top: 20rpx;
}

.picker-item {
  line-height: 50px;
  text-align: center;
}

/* 任务弹窗 */
.task-modal {
  background-color: #FFFFFF;
  border-radius: 20rpx;
  width: 600rpx;
  padding: 30rpx;
}

.modal-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
}

.modal-content {
  margin-bottom: 30rpx;
}

.input-group {
  margin-bottom: 20rpx;
}

.input-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.input-field {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #EEEEEE;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.time-picker {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #EEEEEE;
  border-radius: 10rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
}

.picker-value {
  font-size: 28rpx;
  color: #333;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
}

.cancel-button, .confirm-button, .delete-button {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  margin: 0 10rpx;
}

.cancel-button {
  background-color: #F5F5F5;
  color: #666;
}

.confirm-button {
  background-color: #7766E7;
  color: #FFFFFF;
}

.delete-button {
  background-color: #FE748B;
  color: #FFFFFF;
}

/* 删除确认弹窗 */
.confirm-modal {
  background-color: #FFFFFF;
  border-radius: 20rpx;
  width: 600rpx;
  padding: 30rpx;
}

.confirm-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20rpx;
}

.confirm-content {
  font-size: 32rpx;
  color: #666;
  text-align: center;
  margin-bottom: 30rpx;
}

.confirm-buttons {
  display: flex;
  justify-content: space-between;
}

/* 添加任务按钮 */
.add-task-btn {
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  height: 90rpx;
  background-color: #7766E7;
  color: #FFFFFF;
  border-radius: 45rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(119, 102, 231, 0.3);
}
</style>